﻿<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>开票申请</title>
<!-- 下拉框 -->
<link rel="stylesheet" href="static/ace/css/chosen.css" />
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

<meta name="description" content="" />
<meta name="viewport"
	content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
	

<link rel="stylesheet" href="static/ace/css/bootstrap.css" />
<link rel="stylesheet" href="static/ace/css/font-awesome.css" />

<!-- text fonts -->
<link rel="stylesheet" href="static/ace/css/ace-fonts.css" />
<!-- ace styles -->
<link rel="stylesheet" href="static/ace/css/ace.css"
	class="ace-main-stylesheet" id="main-ace-style" />
<script type="text/javascript" src="static/js/jquery-1.7.2.js" /></script>
<script type="text/javascript">
			$(top.hangge());
		
</script>
<!--提示框-->
<script type="text/javascript" src="static/js/jquery.tips.js"></script>
</head>
<body class="no-skin">
	<div class="main-container" id="main-container">
		<div class="main-content">
			<div class="main-content-inner">
				<div class="page-content">
					<div class="row">
						<div class="col-xs-12">
							<form method="post" id="shipownerForm">
								<fieldset>
									<table style="margin-top: 5px;"
										class="table table-striped table-bordered table-hover">
										<tr>
										    
											<td style="width:100px; text-align: right; padding-top: 13px;">发票单位:<input type="hidden"  name="checkId" id="checkId" value="${pd.checkId}"/><input type="hidden" id="checkCode" name="checkCode" value="${pd.checkCode}"/>><input type="hidden"  name="checkDept" id="checkDept" value="${pd.checkDept}"/></td>
											<td colspan="3"><select  name="invoiceDept" id="invoiceDept"    style="width: 98%;" ></select></td>                                          
											<td colspan="5"  style="text-align:right"><input type="checkbox"  name="adjustTaxRate" id="adjustTaxRate"  style="width:50p;hight:50px;" />批量更改税率</td>
											
											 
											<td style="width:80px; text-align: left; padding-top: 13px;" colspan="4"><select name="taxRateCombox" id="taxRateCombox"    style="width: 98%;" ></select></td>
																				
											
									       
									   </tr>
									   <tr>
									        <td style="width:80px; text-align: right; padding-top: 13px;">平均汇率:</td>
											<td colspan="3"><input type="text" name="exchangeRate" id="exchangeRate" value="${data.rate}" placeholder="请输入汇率"  onkeyup="fmt(this.value)" maxlength="32" style="width: 98%;"/></td>
											<td></td>
											<td colspan=3>发票名目:<select id="openTicketFeeType" name="openTicketFeeType" value="${data.feeName}" style="width: 120px;" onchange="onTicketFeeChange(this.value)" ></select></td>	
											<td>税率
											<input  id="opentTicketTaxRate" name="opentTicketTaxRate" style="width: 50px;" onkeyup="clearNoNum(this)" />
											</td>
											<td>含税价
											<input  id="opentTicketTaxPrice" name="opentTicketTaxPrice" onkeyup="clearNoNum(this)" style="width: 100px;"/>
											</td>	
											<td>箱量
											<input  id="opentTicketContainerNum" name="opentTicketContainerNum" style="width: 50px;" onkeyup="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" 
											onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}"/>
											</td>
											<td>币种
											<select  id="opentTicketCurrency" name="opentTicketCurrency" style="width: 60px;">
											    <option>RMB</option>
											    <option>USD</option>
											</select>
											</td>											
                                            <td><a class="btn btn-xs btn-success">
 											<i class="ace-icon fa fa-pencil-square-o bigger-120" onclick="addInvoiceItems();">添加</i> 
 											</a></td>
<!-- 											<td colspan="1" style="width:80px; text-align: right; padding-top: 13px;"></td> -->
<!-- 											<td colspan="2"></td> -->
										</tr>
										<tr>
										<td style="width:80px; text-align: right; padding-top: 13px;">开票币种:</td>
											<td><input id="invoiceCurRmb" name="invoiceCurRmb" type="checkbox"  maxlength="32" style="width: 30px;" />RMB</td>
											
											<td><input id="rmbAmount" name="rmbAmount" type="text"  maxlength="32" style="width: 98%;" value="${pd.rmb}" /></td>
											<td colspan=2>发票类型<select  id="invoiceType"  name="invoiceType" style="width: 98%;"></select></td>										
											<td rowspan="3" colspan="8"> <input name='txtTRLastIndex' type='hidden' id='txtTRLastIndex' value="1" />
											  <table id="simple-table-invoice_items" class="table table-striped table-bordered table-hover" style="margin-top:5px;">
												<thead>
													<tr>
														<th class="center">发票名目</th>
														<th class="center">税率</th>
														<th class="center">含税金额</th>
														<th class="center">箱量</th>
														<th class="center">币种</th>
														<th class="center">操作</th>
													</tr>
												</thead>
											</table>
											</td>
										</tr>
										<tr>
										    <td></td>
											<td><input id="invoiceCurUsd" name="invoiceCurUsd" type="checkbox"  maxlength="32" style="width: 30px;" />USD</td>
											
											<td><input  id="usdAmount" name="usdAmount" type="text"  maxlength="32" style="width: 98%;" value="${pd.usd}" /></td>
											<td colspan=2>发票类型<select  id="invoiceTypeUsd"  name="invoiceTypeUsd" style="width: 98%;"></select></td>		
											
<!-- 											<td style="text-align: left;" colspan="10"> -->
<!-- 											<a class="btn btn-xs btn-success">  -->
<!-- 											<i class="ace-icon fa fa-pencil-square-o bigger-120" onclick="add();">添加</i> -->
<!-- 											</a></td> -->
										</tr>
                                       <tr>
                                          <td>RMB税率</td>
                                          <td colspan="4">
                                             <table id="simple-table-t" class="table table-striped table-bordered table-hover" style="margin-top:5px;">
												<thead>
													<tr>
														<th class="center">费用名称</th>
														<th class="center">税率</th>
														<th class="center">含税价</th>
														
													</tr>
												</thead>
												
											</table>
                                         </td>
                                         
                                       </tr>
										<tr>
										<td rowspan=2>备注</td>
										<td rowspan=2 colspan=7><textarea id="remark" name="remark"  style="width: 98%;" ></textarea></td>
										</tr>
										<tr>
									     
											<td><a class="btn btn-xs btn-success"> 
											<i  class="ace-icon fa fa-pencil-square-o bigger-120" onclick="save();">保存</i>
											</a></td>
											<td ><a class="btn btn-xs btn-success"> 
											<i class="ace-icon fa fa-pencil-square-o bigger-120"  onclick="closeDialog();">关闭</i>
											</a></td>
									   </tr>
									</table>
								</fieldset>
								   
								      
								
							</form>
						



						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
<script type="text/javascript"
       src="<%=path%>/static/js/settlement/invoice_app_review.js?${staticFileVer}"></script>
</body>
<script type="text/javascript">
function onfreeNameChange(){
	var x=document.getElementById("feeName");
	
	var param={};
	param.checkId=$("#checkId").val();
	param.index=x.selectedIndex;
	$(top.callService("post","/scm/incomeAcct/getFeeRelativeList",param,function (data) {
	
		   var arr =JSON.parse( data );
		   $("#orgTaxRate").val(toPercent(arr[0].taxRate));
		   $("#orgTaxRate").text(toPercent(arr[0].taxRate));
		   $("#orgAmount").val(arr[0].price);
		   
	},null,"html"));
}
/*小数转百分数*/
function toPercent(point){
    var str=Number(point*100).toFixed(1);
    str+="%";
    return str;
}
/*百分数转小数*/
function toPoint(percent){
    var str=percent.replace("%","");
    str= str/100;
    return str;
}
/*选择自定义时给原税率和原金额值*/
function oncustomFee(){
	
	var flag =document.getElementById("customFee").checked;
	if(flag){
		var x=document.getElementById("feeName");
		
		var param={};
		param.checkId=$("#checkId").val();
		param.index=x.selectedIndex;
		$(top.callService("post","/SCM/incomeAcct/getFeeRelativeList",param,function (data) {
			
			   var arr =JSON.parse( data );
			   $("#orgTaxRate").val(toPercent(arr[0].taxRate));
			   $("#orgTaxRate").text(toPercent(arr[0].taxRate));
			   $("#orgAmount").val(arr[0].price);
			   
		},null,"html"));
	}
	
}
function add(){
	
	var flag =document.getElementById("customFee").checked;
	if(!flag) {alert("请选择自定义进行费用拆分税金！");return;}
	if($("#taxPricediv").val()==""){alert("请填写拆分金额！");return;}
	
	var fee = document.getElementById("feeName");        
	var index = fee.selectedIndex;        
	feeId = fee.options[index].value;       
	
	
	var result = adjustDivAmount(parseFloat($("#orgAmount").val()),parseFloat($("#taxPricediv").val()));
	if(result<0)
	{
	   alert("拆分金额不能大于原费用金额！");return;
	}
	var html="";
	 html+="<tr><td class='center' style='width: 30px;' title="+feeId+">"+$("#taxRatediv").val()+"</td><td class='center'>"+$("#taxPricediv").val()+"</td></tr>";
		
     $("#simple-table_add").append(html);  
}
/*判断是否拆分的金额大于原金额*/
// function adjustDivAmount(orgAmount,curVal){
	
// 	      var tb=document.getElementById("simple-table_add");    //获取table对像
// 	      var rows=tb.rows;
// 	      for(var i=1;i<rows.length;i++){    //--循环所有的行
// 	        var cells=rows[i].cells;
	         
// 	        orgAmount = orgAmount- parseFloat(cells[1].innerHTML);
// 	      }
// 	      var result = orgAmount-parseFloat(curVal);
// 	      return result;
	    
// }

function save(){
	
	var flag =document.getElementById("invoiceCurRmb").checked;
	var flag1=document.getElementById("invoiceCurUsd").checked;
	if(!flag && !flag1)  { alert("请选择开票币种！");return;}
	var curreny="";
	if(flag) curreny+="RMB,";
	if(flag1) curreny+="USD";
	var rmbAmount=$("#rmbAmount").val();
	var usdAmount=$("#usdAmount").val();
	var invoiceDept = document.getElementById("invoiceDept");        
	var index = invoiceDept.selectedIndex;        
	var deptVal = invoiceDept.options[index].value;        
	var deptTxt = invoiceDept.options[index].text;
	var exgRate = $("#exchangeRate").val();
	var invoiceType = $("#invoiceType").val();//RMB
	var invoiceTypeUsd= $("#invoiceTypeUsd").val();//USD
	var invoiceTypeTxt="";
	var invoiceTicketId="";
	var invoiceTicketName="";
	var batchUpdateTaxRate=0;
	var batchUpdateTaxRateVal="";
	var feeId=0;
	var feeTxt="";
	switch(invoiceType){
		
		case "1":
			invoiceTypeTxt="普通发票";
			break;
		case "2":
			invoiceTypeTxt="专用发票";
			break;
		case "3":
			invoiceTypeTxt="专用收据";
			break;
		case "4":
			invoiceTypeTxt="海关缴款书";
			break;			
		case "5":
			invoiceTypeTxt="铁路运单";
			break;
		default:
				
	   }
	var isChecked = $("#adjustTaxRate").prop("checked");
	if(isChecked){		
		
		if($("#batchUpdate").prop("checked"))//批量
		{
			batchUpdateTaxRate=1;
			batchUpdateTaxRateVal = $("#taxRateCombox").val();
			
		}else{    //拆分处理
			
			var fee = document.getElementById("feeName");        
			var index = fee.selectedIndex;        
			feeId = fee.options[index].value;        
			feeTxt = fee.options[index].text;
			
		}
		
	}
	
	var rmbTaxRateList=[];	
	  var tb=document.getElementById("simple-table-t");    //获取table对像
	    var rows=tb.rows;
	      for(var i=1;i<rows.length;i++){    //--循环所有的行
	        var cells=rows[i].cells;
	         
	         var rmbinfo = {taxrate:+cells[0].innerHTML,amount:cells[1].innerHTML};
	         //alert(rmbinformbinfo);
	         //rmbTaxRateList[i-1]=rmbinfo;
	}
	      
//       var divTaxRateList=[];	
// 	  var tb=document.getElementById("simple-table_add");    //获取table对像
// 	    var rows=tb.rows;
// 	      for(var i=1;i<rows.length;i++){    //--循环所有的行
// 	        var cells=rows[i].cells;
	         
// 	         var divinfo = {feeid:cells[0].title,taxrate:+cells[0].innerHTML,amount:cells[1].innerHTML};
	         
// 	         divTaxRateList[i-1]=divinfo;
// 	}
  //alert(1);
  var rmbTaxRateList=[];	
  var tb=document.getElementById("simple-table-invoice_items");    //获取table对像
    var rows=tb.rows;
      var json="";
      for(var i=1;i<rows.length;i++){  
        var cells=rows[i].cells;
         var s=toXmlDom(cells[0].innerHTML);
         json=json+"{";
         json=json+getInvoiceItemInfo(0,cells[0].innerHTML)+",";
         json=json+getInvoiceItemInfo(1,cells[1].innerHTML)+",";
         json=json+getInvoiceItemInfo(2,cells[2].innerHTML)+",";
         json=json+getInvoiceItemInfo(3,cells[3].innerHTML)+",";
         json=json+getInvoiceItemInfo(4,cells[4].innerHTML);
         json=json+"},"
     }
  json=json.substring(0,json.length-1);
 
  var param={};
  param.curreny=curreny;
  param.rmbAmount=rmbAmount;
  param.usdAmount=usdAmount;
  param.dept_id=deptVal;
  param.dept_name=deptTxt;
  param.exchangeRate=exgRate;
  param.checkId=$("#checkId").val();
  param.checkCode=$("#checkCode").val();
 // param.rmbTaxRateList=JSON.stringify(rmbTaxRateList);
 // param.divTaxRateList=JSON.stringify(divTaxRateList);
  param.invoiceType=invoiceType;
  param.invoiceTypeTxt=invoiceTypeTxt;
  param.remark=$("#remark").val();  
  param.invoiceFeeName=document.getElementById("openTicketFeeType").options[document.getElementById("openTicketFeeType").options.selectedIndex].text;
  param.invoiceFeeId=$("#openTicketFeeType").val();
  param.json=json;
	 
	//param.index=x.selectedIndex;
	$(top.callService("post","/scm/incomeAcct/saveInvoiceApp",param,function (data) {
		 if(data=="sucess")
		 {
		    alert("申请成功！")
		 }
// 		   var arr =JSON.parse( data );
// 		   $("#orgTaxRate").val(toPercent(arr[0].taxRate));
// 		   $("#orgTaxRate").text(toPercent(arr[0].taxRate));
// 		   $("#orgAmount").val(arr[0].price);
		   
	},null,"html"));
}
function getInvoiceItemInfo(index,html){
	 var s=toXmlDom(html);
     var json="";
     $(s).find("input").each( //得到每一个标签
    	     function(id,item){
    	      var val=$(item)[0].attributes.value.value;
    	      //alert($(item).find("value").context.attributes.value.value);
    	      json = json+JSON.stringify(index)+":"+JSON.stringify(val);
     });
     
     return json;
}
function onTicketFeeChange(param){
	
	var para={};
	para.id=param;
	
	$(top.callService("post","/scm/incomeAcct/getChangeTicketFee",para,function (data) {
		
    var arr =JSON.parse( data );
    $("#opentTicketTaxRate").val(arr.taxRate);
	},null,"html"));
}
function closeDialog()
{
	Dialog.getInstance('0').cancelButton.onclick.apply(Dialog.getInstance('0').cancelButton,[]);
}
function addInvoiceItems()
{
		var feeType = document.getElementById("openTicketFeeType"); 
		var index = feeType.selectedIndex;        
		feeId = feeType.options[index].value;
		//feeId = $("#openTicketFeeType").val();
		var feeTxt = feeType.options[index].text;
		var taxRate = $("#opentTicketTaxRate").val();
		var taxPrice = $("#opentTicketTaxPrice").val();
		var containerNum = $("#opentTicketContainerNum").val();
		var currency = $("#opentTicketCurrency").val();
		//处理逻辑,根据业务类别，判断不是外贸的不能开0税率，是外贸的不能开其它税率的
		if(adjustItemFeeRepeat(feeId)) return;
		var html="";	
		var txtTRLastIndex = document.getElementById("txtTRLastIndex");
		var rowID = parseInt(txtTRLastIndex.value);
		var tb=document.getElementById("simple-table-invoice_items");    //获取table对像
		var rows=tb.rows;

	   /*var tableRow=tb.insertRow(rows.length);
	    var Cell_0=tableRow.insertCell(0);
	    Cell_0.id=rowID+1;
	    Cell_0.name=rowID+1;
	    Cell_0.innerHTML='<input value="'+feeTxt+'"  readonly="false"/>';
	    Cell_0.className="center";
	    Cell_0.title=feeId;
	    
	    var Cell_1=tableRow.insertCell(1);
	    Cell_1.id=rowID+1;
	    Cell_1.name=rowID+1;
	    Cell_1.innerHTML='<input value="'+taxRate+'"  readonly="false"/>';
	    Cell_1.className="center";
	    Cell_1.title=feeId;*/
		
		
	  // html+="<tr><td class='center' title="+feeId+"><input value='"+feeTxt+"' readonly=false/></td><td class='center'><input value='"+taxRate+"' readonly=false/></td></tr>";
		
      // $("#simple-table-invoice_items").append(html);
		var txtTRLastIndex = document.getElementById("txtTRLastIndex");
		var rowID = parseInt(txtTRLastIndex.value);
		
		var tb=document.getElementById("simple-table-invoice_items");    //获取table对像
		//添加行
		var newTR = tb.insertRow(tb.rows.length);
		newTR.id = "SignItem" + rowID;		
		//发票名目
		var newNameTD=newTR.insertCell(0);
		
		newNameTD.innerHTML = "<input name='feeTxt" + rowID + "' id='feeTxt" + rowID + "' type='text' style='width:80px' size='12' value='"+feeTxt+"' />";
		
		//税率
		var newRateTD=newTR.insertCell(1);
		
		newRateTD.innerHTML = "<input name='taxRate" + rowID + "' id='taxRate" + rowID + "' type='text' style='width:80px' size='12' value='"+taxRate+"' />";
		
		//金额
		var newPriceTD=newTR.insertCell(2);
		//添加列内容
		newPriceTD.innerHTML = "<input name='taxPrice" + rowID + "' id='taxPrice" + rowID + "' type='text' style='width:80px' size='20' value='"+taxPrice+"' />";
		
		//金额
		var newContainerNumTD=newTR.insertCell(3);
		//添加列内容
		newContainerNumTD.innerHTML = "<input name='containerNum" + rowID + "' id='containerNum" + rowID + "' type='text' style='width:80px' size='20' value='"+containerNum+"' />";
		
		//金额
		var newCurrencyTD=newTR.insertCell(4);
		//添加列内容
		newCurrencyTD.innerHTML = "<input name='currency" + rowID + "' id='currency" + rowID + "' type='text' style='width:80px' size='20' value='"+currency+"' />";
		
		//添加列:删除按钮
		var newDeleteTD=newTR.insertCell(5);
		//添加列内容
		newDeleteTD.innerHTML = "<div align='center' style='width:40px'><a href='javascript:;' onclick=\"DeleteSignRow('SignItem" + rowID + "')\">删除</a></div>";
		//将行号推进下一行
		txtTRLastIndex.value = (rowID + 1).toString() ;	
}
function adjustItemFeeRepeat(param)
{
	
	
	  var flag=false;
	  var tb=document.getElementById("simple-table-invoice_items");    //获取table对像
	  var rows=tb.rows;
	  for(var i=1;i<rows.length;i++){    
	        var cells=rows[i].cells;
	      var feeId= getAttributeValue(cells[0],"title");
	      if(feeId==param){
	    	  alert("费用项目已添加");
	    	  flag= true;
	    	  break;
	    	 
	      }
	 }
	  return flag;
}
function getAttributeValue (xmlNode,attrName){
    if(!xmlNode)return "" ;
    if(!xmlNode.attributes) return "" ;   
    if(xmlNode.attributes[attrName]!=null) return xmlNode.attributes[attrName].value ;
    if(xmlNode.attributes.getNamedItem(attrName)!=null)  
    	return xmlNode.attributes.getNamedItem(attrName).value;
    return "" ;
}
//删除指定行
function DeleteSignRow(rowid){
var signFrame = document.getElementById("simple-table-invoice_items");
var signItem = findObj(rowid,document);

//获取将要删除的行的Index
var rowIndex = signItem.rowIndex;

//删除指定Index的行
signFrame.deleteRow(rowIndex);

//重新排列序号，如果没有序号，这一步省略
for(i=rowIndex;i<signFrame.rows.length;i++){
signFrame.rows[i].cells[0].innerHTML = i.toString();
}
}
function findObj(theObj, theDoc)
{ 
var p, i, foundObj; 
if(!theDoc) theDoc = document; 
if( (p = theObj.indexOf("?")) > 0 && parent.frames.length) 
{    theDoc = parent.frames[theObj.substring(p+1)].document;    
     theObj = theObj.substring(0,p); } if(!(foundObj = theDoc[theObj]) && theDoc.all) 
     foundObj = theDoc.all[theObj]; for (i=0; !foundObj && i < theDoc.forms.length; i++)     
   foundObj = theDoc.forms[i][theObj]; for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)     
   foundObj = findObj(theObj,theDoc.layers[i].document); if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);    
   return foundObj;
}

function clearNoNum(obj){ 
    obj.value = obj.value.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符  
    obj.value = obj.value.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的  
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$","."); 
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数  
    if(obj.value.indexOf(".")< 0 && obj.value !=""){//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额 
        obj.value= parseFloat(obj.value); 
    } 
} 
//字符串转化为xml
function toXmlDom(source){
    var xmlDoc = null;
    if (window.ActiveXObject) {
        var ARR_ACTIVEX = ["MSXML4.DOMDocument","MSXML3.DOMDocument","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XmlDom"];
        var XmlDomflag = false;
        for (var i = 0;i < ARR_ACTIVEX.length && !XmlDomflag ;i++) {
            try {
                var objXML = new ActiveXObject(ARR_ACTIVEX[i]);
                xmlDoc = objXML;
                XmlDomflag = true;
            } catch (e) {
            }
        }
        if(xmlDoc){ 
            xmlDoc.async = false;
            xmlDoc.loadXML(source);
        }
    }else{
     var parser=new DOMParser();
     var xmlDoc=parser.parseFromString(source,"text/xml");
   }
    return xmlDoc;
}
</script>

</html>